package com.by.service.impl.impl;

import com.by.bean.Forwarder;
import com.by.bean.User;
import com.by.bean.UserType;
import com.by.common.bean.PageBean;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.ex.BusinessException;
import com.by.common.utils.Assert;
import com.by.mapper.ForwarderMapper;
import com.by.mapper.UserMapper;
import com.by.query.ForwarderQuery;
import com.by.service.impl.ForwarderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service
public class ForwarderServiceImpl extends BaseServiceImpl<Forwarder,  ForwarderMapper>implements ForwarderService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    ForwarderMapper forwarderMapper;

    @Override
    public PageBean query(ForwarderQuery query) {
        //分页查询
        PageHelper.startPage(query.getPage(),query.getPageSize());//后面紧跟查询
        List<Map> list = baseMapper.query(query);
        PageInfo info = new PageInfo(list);
        return new PageBean(query.getPage(),query.getPageSize(),info.getTotal(),list);
    }

    @Transactional
    @Override
    public int save(Forwarder entity) {
        //检查用户是否存在
        int c = userMapper.queryUserByUserName(entity.getAccount());
        if (c > 0){
            throw new BusinessException("该账号已存在");
        }
        // 保存货代用户信息
        User user = new User(entity.getAccount(), entity.getPassword(), UserType.FORWARDER_USER);
        int rs = userMapper.save(user);
        Assert.isZero(rs, "货代用户货代失败");
        //设置货代id
        entity.setId(user.getId());
        return super.save(entity);
    }

    @Transactional
    @Override
    public int delete(Serializable id) {
        //删除用户信息
        int rs = userMapper.delete(id);
        Assert.isZero(rs, "删除用户信息失败");
        return super.delete(id);
    }

    @Transactional
    @Override
    public Forwarder get(Serializable id) {
        return forwarderMapper.getForwarderWithAccountAndPassword(id);
    }
    @Transactional
    @Override
    public int update(Forwarder entity) {
        return super.update(entity);
    }
}
